package LeetCode.leetcode383;

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println(canConstruct3("a","b"));
    }
    /**
     * 自写题解
     * @param ransomNote
     * @param magazine
     * @return
     */
    public boolean canConstruct(String ransomNote, String magazine) {
        char c;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < magazine.length(); i++) {
            c = magazine.charAt(i);
            map.compute(c, (k, v) -> (v == null) ? 1 : v + 1);
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            c = ransomNote.charAt(i);
            if (map.containsKey(c)) {
                map.compute(c, (k, v) -> (v - 1));
                if (map.get(c) < 0)
                    return false;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 利用数组代替hash表，效率将得到提升
     * @param ransomNote
     * @param magazine
     * @return
     */
    public boolean canConstruct2(String ransomNote, String magazine) {
        //记录杂志字符串出现的次数
        int[] arr = new int[26];
        int temp;
        for (int i = 0; i < magazine.length(); i++) {
            temp = magazine.charAt(i) - 'a';
            arr[temp]++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            temp = ransomNote.charAt(i) - 'a';
            //对于金信中的每一个字符都在数组中查找
            //找到相应位减一，否则找不到返回false
            if (arr[temp] > 0) {
                arr[temp]--;
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * review
     * @param ransomNote
     * @param magazine
     * @return
     */
    public static boolean canConstruct3(String ransomNote, String magazine) {
        int[] table = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            table[magazine.charAt(i) % 26]++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            if (table[ransomNote.charAt(i) % 26]-1 < 0 )
                return false;
        }
        return true;
    }
}
